$rangeStart = $args[0]
$rangeEnd = $args[1]

function IsAvailablePort([int]$portNumber)
{
	$availablePort = $TRUE;

	$connections = netstat -a -p TCP

	for($i = 4; $i -le $connections.Length; $i++)
	{
		if ($connections[$i] -ne $NULL)
		{
			$connection = $connections[$i].ToString();
			$portStr = $connection.Substring($connection.ToString().IndexOf(':') + 1)
			$portStr = $portStr.SubString(0, $portStr.ToString().IndexOf(' ') + 1);
			
			$port = [int]$portStr;
			
			if ($port -eq $portNumber)
			{
				$availablePort = $FALSE;
				break;
			}
		}
	}

	return $availablePort;
}

function RetrieveFirstAvailablePort([int]$rangeStart, [int]$rangeEnd)
{
	# If no ports are available, then returns -1
	$availablePort = -1;
	
	for ($portNo = $rangeStart; $portNo -le $rangeEnd + 1; $portNo++)
	{
		if (IsAvailablePort -portNumber $portNo)
		{
			$availablePort = $portNo;
			break;
		}
	}
	
	return $availablePort;
}

Write-Output "Searching available port: $rangeStart to $rangeEnd...";
$labsPort = RetrieveFirstAvailablePort -rangeStart $rangeStart -rangeEnd $rangeEnd;
Write-Output "First available port for Labs Web Site: $labsPort";
$rangeStart = $labsPort + 1;
Write-Output "Searching available port: $rangeStart to $rangeEnd...";
$demosPort = RetrieveFirstAvailablePort -rangeStart $rangeStart -rangeEnd $rangeEnd;
Write-Output "First available port for Demos Web Site: $demosPort";

.\setupWebSites.cmd $labsPort $demosPort

$currentLocation = Get-Location;

if ($labsPort -ne 50000)
{
	Write-Warning "The port 50000 is already in use. PHPTrainingKitLabs web site is created using the port $labsPort";
	.\renameHtmlLinks.ps1 "../../../../../SQLServer.htm" "http://localhost:50000" "http://localhost:$labsPort";
	Set-Location $currentLocation;
}

if ($demosPort -ne 50001)
{
	Write-Warning "The port 50001 is already in use. PHPTrainingKitDemos web site is created using the port $demosPort";
	.\renameHtmlLinks.ps1 "../../../../../SQLServer.htm" "http://localhost:50001" "http://localhost:$demosPort"
	Set-Location $currentLocation;
}